<template>
  <div class="tablePageWarp">
    <div>
      <a-form layout="vertical" >
        <a-row :gutter="[16,0]">
          <!-- 任务类型 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('任务类型')">
              <a-select
                :showSearch="true"
                :placeholder="$t('otaTaskType')"
                :allow-clear="true"
                v-model="queryParam.taskBigType"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                @change="refreshData(false)"
                style="width:100%"
              >
                <a-select-option value="0">
                  研发测试任务
                </a-select-option>
                <a-select-option value="1">
                  通道测试任务
                </a-select-option>
                <a-select-option value="2">
                  正式OTA任务
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 任务名称 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('任务名称')">
              <task-select
                :time="taskSelectTime"
                :default-task-id="queryParam.taskId"
                @changeoption="(val) => {changeTask(val, 'taskId');refreshData(true)}"
                :clear="true"
                style="width:100%"
              ></task-select>
            </a-form-model-item>
          </a-col>
          <!-- 升级类型 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('升级类型')">
              <a-select
                :showSearch="true"
                :placeholder="$t('upgradeType')"
                :allow-clear="true"
                v-model="queryParam.upgradeType"
                optionFilterProp="children"
                :filterOption="$commonFun.filterOption"
                @change="refreshData(false)"
                style="width:100%"
              >
                <a-select-option value="0">
                  用户升级-强制升级
                </a-select-option>
                <a-select-option value="1">
                  用户升级-非强制升级
                </a-select-option>
                <a-select-option value="2">
                  自动升级-静默升级
                </a-select-option>
                <a-select-option value="3">
                  自动升级-非静默升级
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 批次号 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('批次号')">
              <a-input v-model="queryParam.batchId" :placeholder="$t('pleaseInput') + '批次号'" @keyup.enter="refreshData(true)"/>
            </a-form-model-item>
          </a-col>
          <!-- 源车辆版本 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('源车辆版本')">
              <a-input v-model="queryParam.normalOriginVer" :placeholder="$t('pleaseInput') + '源车辆版本'" @keyup.enter="refreshData(true)"/>
            </a-form-model-item>
          </a-col>
          <!-- 目标车辆版本 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('目标车辆版本')">
              <a-input v-model="queryParam.normalVersion" :placeholder="$t('pleaseInput') + '目标车辆版本'" @keyup.enter="refreshData(true)"/>
            </a-form-model-item>
          </a-col>
          <!-- 升级结果 -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('升级结果')">
              <a-select
                allow-clear
                show-search
                v-model="queryParam.upgradeResult"
                :placeholder="$t('pleaseSelect')"
                @change="refreshData(false)"
              >
                <!-- <a-select-option v-for="(item, index) in taskVehicleStatusDictCode" :key="index" :value="item.name">
                  {{ item.name }}
                </a-select-option> -->
                <a-select-option value="已唤醒">
                  已唤醒
                </a-select-option>
                <a-select-option value="未唤醒">
                  未唤醒
                </a-select-option>
                <a-select-option value="唤醒失败">
                  唤醒失败
                </a-select-option>
                <a-select-option value="检测成功">
                  检测成功
                </a-select-option>
                <a-select-option value="检测失败">
                  检测失败
                </a-select-option>
                <a-select-option value="下载失败">
                  下载失败
                </a-select-option>
                <a-select-option value="ECU下载中">
                  ECU下载中
                </a-select-option>
                <a-select-option value="下载成功">
                  下载成功
                </a-select-option>
                <a-select-option value="安装成功">
                  安装成功
                </a-select-option>
                <a-select-option value="安装中">
                  安装中
                </a-select-option>
                <a-select-option value="安装失败">
                  安装失败
                </a-select-option>
                <a-select-option value="未知">
                  未知
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 数据上报时间-->
          <a-col :md="6" :sm="24">
            <a-form-model-item :label="$t('数据上报时间')">
              <a-range-picker
                @change="selectDateRange"
                v-model="normalTime"
                :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                }"
                style="width: 100%"
                :placeholder="['上报时间-开始','上报时间-结束']"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24" style="margin-top: 22px;">
            <div class="searchBtns">
              <a-button-group>
                <auth-button :auth="openType==='formal'?managePerms.vehicle2.fotaView:managePerms.vehicle2.testFotaView" type="primary" @click="refreshData(true)">
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </auth-button>
                <a-button @click="initiSelectValue">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="commonTableSty">
      <s-table
        class="h100"
        ref="table"
        :columns="columns"
        :data="loadData"
        :scrollX="900"
        :rowKey="(record, index) => index"
        size="default" >
        <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
          <table-ellipsis :text="text || '-' " :key="column.key"></table-ellipsis>
        </template>
        <template slot="taskName" slot-scope="text, record">
          <a @click="showTaskDetails(record)">
            <table-ellipsis :text="text"></table-ellipsis>
          </a>
        </template>
        <template slot="taskVehicleUpgradeStatus" slot-scope="text, record">
          <table-ellipsis :text="text?$store.getters.getDictCodeObj('taskVehicleUpgradeStatusDictCode')[text]||'-':'-'"></table-ellipsis>
        </template>
        <template #taskBigType="text, record">
          <span v-if="record.taskBigType===0" >研发测试任务</span>
          <span v-if="record.taskBigType===1" >整车测试任务</span>
          <span v-if="record.taskBigType===2" >正式OTA任务</span>
          <span v-if="record.taskBigType===30" >通道测试任务</span>
        </template>
        <template #upgradeType="text, record">
          <span v-if="record.upgradeType===0">用户升级-强制升级</span>
          <span v-if="record.upgradeType===1">用户升级-非强制升级</span>
          <span v-if="record.upgradeType===2">自动升级-静默升级</span>
          <span v-if="record.upgradeType===3">自动升级-非静默升级</span>
        </template>
        <template slot="operation" slot-scope="text, record">
          <span style="display: flex;">
            <auth-button
              :auth="openType==='formal'?managePerms.vehicle2.ecuUpgradeDetails:managePerms.vehicle2.testEcuUpgradeDetails"
              type="primary"
              :ghost="true"
              size="small"
              style="margin-right: 12px;"
              @click="showEcuUpgradeDetails(record)"
            >{{ $t('ECU升级详情') }}</auth-button>
            <auth-button
              :auth="openType==='formal'?managePerms.vehicle2.stopTask:managePerms.vehicle2.testStopTask"
              type="primary"
              :ghost="true"
              size="small"
              :disabled="record.taskStatus==16"
              @click="cancelTask(record)"
            >{{ $t('停止车辆任务') }}</auth-button>
          </span>
        </template>
      </s-table>
    </div>
    <!-- ECU升级详情 -->
    <a-modal
      :width="1180"
      :visible="ecuUpgradeDetailsVisible"
      :destroyOnClose="true"
      title="ECU升级详情"
      :bodyStyle="{ height: '500px'}"
      @cancel="shutEcuUpgradeDetails">
      <ecu-upgrade-details :taskId="taskId" :upgradeInfo="upgradeInfo"></ecu-upgrade-details>
      <template #footer>
        <slot name="footer">
          <a-button cancel @click="shutEcuUpgradeDetails">{{ $t('cancel') }}</a-button>
        </slot>
      </template>
    </a-modal>
    <!-- 任务名称任务详情 -->
    <custom-modal
      :width="1100"
      :visible="taskDetailsVisible"
      title="任务详情"
      :destroyOnClose="true"
      class="largeVersionPopup"
      @cancel="handleCancelTaskDetails"
      modalCls=".largeVersionPopup"
      :isOkBtn="false"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }">
      <fota-historical-mission-details :id="id" :vehicleId="vehicleId"></fota-historical-mission-details>
    </custom-modal>
  </div>
</template>
<script>
import { STable } from '@/components'
import moment from 'moment'
import AuthButton from '@/components/AuthButton'
import CustomModal from '@/components/CustomModal/index.vue'
import { fotaHistoryListColumns } from '@/views/vehicle/config/list'
import EcuUpgradeDetails from '@/views/vehicle/components/EcuUpgradeDetails.vue'
import FotaHistoricalMissionDetails from '@/views/vehicle/components/FotaHistoricalMissionDetails.vue'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import TaskSelect from '@/views/components/TaskSelect'
import { mapState } from 'vuex'
import {managePerms} from '@/config/permission/index'
const initQueryParam = {
  taskBigType: undefined,
  taskId: undefined,
  upgradeType: undefined,
  upgradeResult: undefined,
  normalVersion: undefined,
  normalOriginVer: undefined,
  batchId: undefined
}
export default {
  components: {
    STable,
    AuthButton,
    CustomModal,
    EcuUpgradeDetails,
    FotaHistoricalMissionDetails,
    TableEllipsis,
    TaskSelect
  },
  watch: {
    activeKey: {
      handler (val) {
        if (val === 'FotaHistoryList') {
          this.refreshData()
        }
      }
    }
  },
  props: {
    activeKey: {
      type: String,
      default: ''
    },
    vin: {
      type: String,
      default: ''
    },
    openType: {
      type: String,
      default: ''
    },
    vehicleId: {
      type: String,
      default: ''
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter(item => !item.special)
    },
    ...mapState({
      taskVehicleStatusDictCode: (state) => state.dict.taskVehicleStatusDictCode
    })
  },
  created () {
    this.$store.dispatch('getTaskVehicleStatusDictCodeData')
    this.$store.dispatch('getTaskVehicleUpgradeStatusDictCodeData')
  },
  data () {
    return {
      managePerms,
      moment,
      columns: [...fotaHistoryListColumns],
      // 列表数据
      tableData: [],
      queryParam: { ...initQueryParam },
      ecuUpgradeDetailsVisible: false,
      taskDetailsVisible: false,
      taskSelectTime: 12344321,
      normalTime: null,
      id: '',
      testType: '',
      // 传值用
      taskId: '',
      upgradeInfo: {}
    }
  },
  methods: {
    // 任务取消
    cancelTask (record) {
      const vm = this
      if (record.taskBigType === 0) {
        vm.testType = 'DEVELOP'
      } else if (record.taskBigType === 1) {
        vm.testType = 'CHANNEL'
      } else {
        vm.testType = 'UAT'
      }
      this.$confirm({
        title: '停止任务',
        content: '请确认是否停止任务？',
        class: 'confirmStyle',
        onOk () {
          vm.$api.cancelTask({ ids: [record.taskId] }, vm.testType).then(() => {
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.refreshData(true) // 刷新页面
          })
        },
        onCancel () {}
      })
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = { ...initQueryParam }
      this.normalTime = undefined
      this.refreshData(true)
    },
    // 上报时间选择
    selectDateRange (date, dateString) {
      this.queryParam.createTimeGte = dateString[0]
      this.queryParam.createTimeLte = dateString[1]
      this.refreshData(true);
    },
    changeTask (val) {
      this.queryParam.taskId = val
    },
    showTaskDetails (record) {
      this.id = record.taskId
      this.taskDetailsVisible = true
    },
    // 关闭任务名称任务详情
    handleCancelTaskDetails () {
      this.taskDetailsVisible = false
    },
    // 打开ECU升级详情
    showEcuUpgradeDetails (record) {
      this.taskId = record.taskId
      this.upgradeInfo.taskName = record.taskName
      this.upgradeInfo.ecuNum = record.ecuNum
      this.upgradeInfo.ecuSuccessNum = record.ecuSuccessNum
      this.upgradeInfo.ecuFailNum = record.ecuFailNum
      this.upgradeInfo.processId = record.processId
      this.upgradeInfo.vin = record.vin
      this.upgradeInfo.taskId = record.taskId
      this.ecuUpgradeDetailsVisible = true
    },
    shutEcuUpgradeDetails () {
      this.ecuUpgradeDetailsVisible = false
    },
    // 刷新
    refreshData (isToFirstPage = false) {
      const vm = this
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      this.tableData = []
      const apiPromise = vm.$api.upgradeMonitorList({ ...parameter, ...JnqueryParam, vin: vm.vin })
      return new Promise((resolve, reject) => {
        return apiPromise.then(res => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
</script>
<style scoped lang="less">
 ::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
::v-deep .ant-modal-body {
  padding-top: 0;
}
</style>
